<!-- 实名认证弹窗 -->
<script lang="tsx">
import { defineComponent, ref, computed, onDeactivated } from 'vue';
import { useUserStore } from '@vben/stores';
import { $t } from '@vben/locales';
import { ElMessage } from 'element-plus';
import Code from '#/components/common/code.vue';
import { getEmailCodeApi } from '#/api';
import { realNameAuthApi } from '#/api/personal';
import setPublicCode from '#/utils/setPublicKey';
import { EmailMatcher, idCardRegex } from '#/utils/constants';

export default defineComponent({
  name: 'RealnameDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:modelValue', 'confirm'],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const userInfo = computed(() => userStore.userInfo);

    const formRef = ref();
    const loading = ref(false);
    const authAlert = ref(false);
    const alertTitle = ref('');

    // 表单数据
    const formData = ref({
      name: '',
      idCard: '',
      email: userInfo.value?.email || '',
      verifyCode: ''
    });



    const visible = computed({
      get: () => props.modelValue,
      set: (val: boolean) => emit('update:modelValue', val)
    });

    // 表单列配置
    const formColumns = [
      {
        prop: 'name',
        label: $t('common.nameTxt'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('common.nameTxt')]),
        required: true,
        formItemProps: {
          class: 'w-full mb-5',
          style: { width: '100%' }
        }
      },
      {
        prop: 'idCard',
        label: $t('common.idCardTxt'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('common.idCardTxt')]),
        required: true,
        formItemProps: {
          class: 'w-full mb-5',
          style: { width: '100%' }
        }
      },
      {
        prop: 'email',
        label: $t('common.emailTxt'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('common.emailTxt')]),
        required: true,
        formItemProps: {
          class: 'w-full mb-5',
          style: { width: '100%' }
        }
      },
      {
        prop: 'verifyCode',
        label: $t('common.verificationCodeTxt'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('common.verificationCodeTxt')]),
        required: true,
        formItemProps: {
          class: 'w-full mb-5',
          style: { width: '100%' }
        }
      }
    ];

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: $t('common.inputPhTxt', [$t('common.nameTxt')]), trigger: 'blur' }
      ],
      idCard: [
        { required: true, message: $t('common.inputPhTxt', [$t('common.idCardTxt')]), trigger: 'blur' },
        { pattern: idCardRegex, message: $t('common.idCardPhTxt'), trigger: 'blur' }
      ],
      email: [
        { required: true, message: $t('common.inputPhTxt', [$t('common.emailTxt')]), trigger: 'blur' },
        { pattern: EmailMatcher, message: $t('common.emailPhTxt'), trigger: 'blur' }
      ],
      verifyCode: [
        { required: true, message: $t('common.inputPhTxt', [$t('common.verificationCodeTxt')]), trigger: 'blur' },
        { pattern: /^\d{6}$/, message: $t('common.verificationCodeFormatTxt'), trigger: 'blur' }
      ]
    };

    // 获取验证码
    const getCode = (callback: Function) => {
      // 手动验证邮箱
      if (!formData.value.email) {
        ElMessage.warning($t('common.inputPhTxt', [$t('common.emailTxt')]));
        return;
      }

      // 验证邮箱格式
      if (!EmailMatcher.test(formData.value.email)) {
        ElMessage.warning($t('common.emailPhTxt'));
        return;
      }

      callback(); // 启动倒计时

      // 调用发送验证码API
      getEmailCodeApi({ email: formData.value.email })
    };

    // 关闭弹窗
    const handleClose = () => {
      visible.value = false;
      // 清理错误状态
      close();
      // 重置表单
      formData.value = {
        name: '',
        idCard: '',
        email: userInfo.value?.email || '',
        verifyCode: ''
      };
      if (formRef.value) {
        formRef.value.resetFields();
      }
    };

    // 关闭错误提示
    const close = () => {
      authAlert.value = false;
    };

    // 确认提交
    const handleConfirm = async () => {
      try {
        // 清理错误状态
        alertTitle.value = '';
        authAlert.value = false;

        const valid = await new Promise((resolve) => {
          formRef.value.validate((isValid: boolean) => {
            resolve(isValid);
          });
        });

        if (!valid) {
          return;
        }

        // 验证码验证
        if (!formData.value.verifyCode) {
          ElMessage.warning($t('common.inputPhTxt', [$t('common.verificationCodeTxt')]));
          return;
        }

        loading.value = true;

        // 调用实名认证API，映射字段名
        const apiData = {
          nameCn: formData.value.name,
          idCard: formData.value.idCard,
          email: formData.value.email,
          verificationCode: formData.value.verifyCode
        };
        apiData.idCard = setPublicCode(apiData.idCard ?? '') || '';

        realNameAuthApi(apiData).then((res) => {
          ElMessage.success($t('common.submitSuccessTxt'));
          emit('confirm', formData.value);
          handleClose();
        }).catch((error) => {
          alertTitle.value = error.message || '';
          authAlert.value = true;
        });
      } catch (error) {
        alertTitle.value = (error as any).message || '';
        authAlert.value = true;
      } finally {
        loading.value = false;
      }
    };

    // 表单数据更新处理
    const handleFormUpdate = (data: any) => {
      formData.value = { ...formData.value, ...data };
    };

    return () => (
      <el-dialog
        v-model={visible.value}
        title={$t('common.realNameAuthTxt')}
        width="480px"
        onClose={handleClose}
        append-to-body
        destroy-on-close
        close-on-click-modal={false}
        class="realname-dialog"
        v-slots={{
          footer: () => (
            <div class="flex justify-end gap-3 px-5">
              <el-button onClick={handleClose}>{$t('common.cancel')}</el-button>
              <el-button
                type="primary"
                onClick={handleConfirm}
                loading={loading.value}
              >
                {$t('common.confirm')}
              </el-button>
            </div>
          )
        }}
      >
        {/* 认证异常 */}
        {authAlert.value && (
          <el-alert title={alertTitle.value} type="error" onClose={close} />
        )}
        <div>
          <base-form
            ref={formRef}
            columns={formColumns}
            modelValue={formData.value}
            rules={formRules}
            label-position="right"
            label-width="78px"
            onUpdate:modelValue={handleFormUpdate}
            v-slots={{
              verifyCode: () => (
                <el-input
                  v-model={formData.value.verifyCode}
                  placeholder={$t('common.inputPhTxt', [$t('common.verificationCodeTxt')])}
                  maxlength={6}
                  v-slots={{
                    append: () => (
                      <Code
                        onGetCode={getCode}
                        authCode={formData.value.email}
                        codeName={$t('common.getCodeTxt')}
                      />
                    )
                  }}
                />
              )
            }}
          />
        </div>
      </el-dialog>
    );
  },
});
</script>

<style>
/* 深度选择器样式调整 - 使用最高权重覆盖原组件样式 */
.realname-dialog :deep(.base-form .base-form-item),
.realname-dialog :deep(.base-form .base-form-item.base-form-item),
:deep(.el-dialog .base-form .base-form-item),
:deep(.el-dialog .base-form .base-form-item.base-form-item),
:deep(.el-dialog__body .base-form .base-form-item) {
  width: 100% !important;
  min-width: 100% !important;
  max-width: 100% !important;
  flex: 0 0 100% !important;
}

:deep(.el-form-item .el-form-item__label) {
  @apply pb-2 font-medium text-right;
}

:deep(.el-form-item .el-form-item__content) {
  @apply flex-1;
}
</style>
